const express = require("express");
const app = express();
const ws = require("nodejs-websocket");
const wsfun = require("./ws/index");
// console.log(wsfun.conf);
ws.createServer(wsfun.conf).listen(8181)
// 跨域中间件
const cors = require("cors");
const joi = require("joi")
// 解析token的中间件
// 配置解析表单数据 只能解析 www-urlencoded 的数据
app.use(express.urlencoded({extended:false}));
app.use(cors());
// 在路由之前封装res.cc
app.use((req,res,next)=>{
    // status 为1 表示失败的情况
    res.cc = function(err,status = 1){
        res.send({
            status,
            message: err instanceof Error?err.message:err
        })
    }
    next()
})
// 一定要在路由之前配置解析token的中间件
app.use("/upload",express.static('upload'));
//3.开放目录
// app.use(express.static(__dirname + '/upload'))
const expressJWT = require("express-jwt");
const config = require("./config");
app.use(expressJWT({
    secret:config.jwtSecret
}).unless({
    path:[/^\/api/,/^\/upload/]
}))

// 路由处理模块
const userRouter = require("./rooter/user");
const userInfoRouter = require("./rooter/userInfo");
const artcateRouter = require("./rooter/artcate");
const articleRouter = require("./rooter/article");
const listRouter = require("./rooter/list")
const commentsRouter = require("./rooter/comments")
app.use("/api",userRouter)
app.use("/my",userInfoRouter)
app.use("/my/artcate",artcateRouter)
app.use("/my/list",listRouter)
app.use("/my/article",articleRouter)
app.use("/my/comment",commentsRouter)
// 定义错误级别的中间件
app.use((err,req,res,next)=>{
    if (err instanceof joi.ValidationError) {
        // 验证失败导致的错误
        return res.cc(err)
    }
    if (err.name==="UnauthorizedError") {
        return res.cc("身份认证失败")
    }
    console.log(err);
        // 未知的错误
    res.cc(err)
})
app.listen(3000,()=>{
    console.log("the serve is runing at 3000 port");
})